import java.io.*;
import java.net.*;
import java.security.*;
import java.util.*;
import javax.net.*;
import javax.net.ssl.*;

public class MF_Client implements Runnable
{
  private DataInputStream din;
  private DataOutputStream dout;

  private KeyStore mfKeyStore;         //La nuestra
  private KeyStore emKeyStore;         //La del EM

  private SSLContext sslContext;
  
  static private final String passphrase = "mfpass";

  static private SecureRandom secureRandom;

  private int id;
  private String resultats; 

  public MF_Client (String host, int port, int id, String resultats) {
    this.id = id;
    this.resultats = resultats;
    connect( host, port );

    new Thread( this ).start();
  }

  private void setupServerKeystore() throws GeneralSecurityException, IOException {
    emKeyStore = KeyStore.getInstance( "JKS" );
    emKeyStore.load( new FileInputStream( "em.public" ), 
                        "public".toCharArray() );
  }

  private void setupClientKeyStore() throws GeneralSecurityException, IOException {
    mfKeyStore = KeyStore.getInstance( "JKS" );
    mfKeyStore.load( new FileInputStream( "mf.private" ),
                       passphrase.toCharArray() );
  }

  private void setupSSLContext() throws GeneralSecurityException, IOException {
    TrustManagerFactory tmf = TrustManagerFactory.getInstance( "SunX509" );
    tmf.init( emKeyStore );

    KeyManagerFactory kmf = KeyManagerFactory.getInstance( "SunX509" );
    kmf.init( mfKeyStore, passphrase.toCharArray() );

    sslContext = SSLContext.getInstance( "TLS" );
    sslContext.init( kmf.getKeyManagers(),
                     tmf.getTrustManagers(),
                     secureRandom );
  }

  private void connect( String host, int port ) {
    try {
      System.out.println( "Wait while secure random numbers are initialized...." );
      this.secureRandom = new SecureRandom(); 
      this.secureRandom.nextInt();
      System.out.println( "Done." );
      
      setupServerKeystore();
      setupClientKeyStore();
      setupSSLContext();

      SSLSocketFactory sf = sslContext.getSocketFactory();
      SSLSocket socket = (SSLSocket)sf.createSocket( host, port ); 

      InputStream in = socket.getInputStream();
      OutputStream out = socket.getOutputStream();

      din = new DataInputStream( in );
      dout = new DataOutputStream( out );
    } catch( GeneralSecurityException gse ) {
      gse.printStackTrace();
    } catch( IOException ie ) {
      ie.printStackTrace();
    }
  }

  public void run() {
    //Leemos el fichero y lo volcamos por el socket
    try{
      dout.writeInt( this.id );
      dout.writeUTF( this.resultats );
    }
    catch (Exception e){e.printStackTrace();}
  }
  public static void main(String args[]){

    new MF_Client("localhost",5555,Integer.parseInt(args[0]),args[1]);

  }
}
